package org.loneranger.sword.offer06;

import java.util.ArrayList;

/**
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 * 输入：head = [1,3,2]
 * 输出：[2,3,1]
 *
 * @author LoneRanger
 * @version 1.0
 */
public class offer06 {
	public static void main(String[] args) {
		ListNode n1 = new ListNode(1);
		ListNode n2 = new ListNode(2);
		ListNode n3 = new ListNode(3);
		ListNode n4 = new ListNode(4);
		ListNode n5 = new ListNode(5);
		n1.next = n2;
		n2.next = n3;
		n3.next = n4;
		n4.next = n5;
		System.out.println(new Solution_1().reversePrint(n1));
	}
}


class Solution {
	public int[] reversePrint(ListNode head) {
		if (head == null) {
			return new int[]{};
		}
		ListNode qian = null;

		int i = 0;
		while (true) {
			if (head == null) {
				break;
			}
			if (head.next == null) {
				head.next = qian;
				qian = head;
				i++;
				break;
			}
			i += 2;
			ListNode n1 = head;
			ListNode n2 = head.next;
			head = n2.next;
			n1.next = qian;
			n2.next = n1;
			qian = n2;
		}
		int[] arr = new int[i];

		for (int j = 0; ; j++) {
			arr[j] = qian.val;
			if (qian.next != null) {
				qian = qian.next;
			} else {
				break;
			}
		}
		return arr;
	}
}


class Solution_1 {

	ArrayList<ListNode> list = new ArrayList<>();

	public int[] reversePrint(ListNode head) {
		if(head == null){
			return new int[0];
		}
		recur(head);
		int[] arr = new int[list.size()];
		for (int i = 0; i < list.size(); i++) {
			arr[i] = list.get(i).val;
		}
		return arr;
	}

	private void recur(ListNode node) {
		if (node.next != null) {
			recur(node.next);
		}
		list.add(node);
		return;
	}

}


